package com.ricky.base.bean;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import lombok.Data;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Ricky
 * @date 2020/11/30
 */
@Data
public class DbClient implements AutoCloseable {
    private String dbPath;
    private ConnectionSource connectionSource;

    public DbClient(String dbPath) throws SQLException {
        this.dbPath = dbPath;
        String databaseUrl = "jdbc:sqlite:" + dbPath;
        connectionSource = new JdbcConnectionSource(databaseUrl);
    }

    public <T> Dao<T, String> getDao(Class<T> clazz) throws SQLException {
        return DaoManager.createDao(connectionSource, clazz);
    }

    public <T> int insert(T data) throws SQLException {
        if (data instanceof Iterable) {
            throw new RuntimeException("请使用 insertList 方法");
        }
        Dao<T, String> dao = getDao((Class<T>) data.getClass());
        return dao.create(data);
    }

    public <T> int insertList(List<T> datas) throws SQLException {
        if (datas.size() == 0) {
            return 0;
        }
        Class<T> aClass = (Class<T>) datas.get(0).getClass();
        Dao<T, String> dao = getDao(aClass);
        return dao.create(datas);
    }

    public <T> int delete(T data) throws SQLException {
        if (data instanceof Iterable) {
            throw new RuntimeException("请使用 deleteList 方法");
        }
        Dao<T, String> dao = getDao((Class<T>) data.getClass());
        return dao.delete(data);
    }

    public <T> int deleteList(List<T> datas) throws SQLException {
        if (datas.size() == 0) {
            return 0;
        }
        Class<T> aClass = (Class<T>) datas.get(0).getClass();
        Dao<T, String> dao = getDao(aClass);
        return dao.delete(datas);
    }

    public <T> int update(T data) throws SQLException {
        Dao<T, String> dao = getDao((Class<T>) data.getClass());
        return dao.update(data);
    }

    public <T> List<T> getAll(Class<T> tClass) throws SQLException {
        Dao<T, String> dao = getDao(tClass);
        return dao.queryForAll();
    }

    public <T> T getById(String id, Class<T> tClass) throws SQLException {
        Dao<T, String> dao = getDao(tClass);
        return dao.queryForId(id);
    }

    @Override
    public void close() throws Exception {
        connectionSource.close();
    }
}
